package xyz.yq56.easytool.utils.image;

import java.awt.image.BufferedImage;
import java.io.InputStream;

import javax.imageio.ImageIO;

import xyz.yq56.easytool.enums.ImageMimeType;
import xyz.yq56.easytool.utils.encrypt.Base64Util;
import xyz.yq56.easytool.utils.http.HttpsUtil;
import xyz.yq56.easytool.utils.io.IoUtil;
import xyz.yq56.easytool.utils.log.LogUtil;

/**
 * @author yi qiang
 * @date 2021/9/17 1:07
 */
public class ImageUtil {

    private ImageUtil() {
    }

    /**
     * 通过此工具类可以很方便的获取到图片的长宽等信息
     *
     * @param url 图片地址
     * @return 图片信息
     */
    public static BufferedImage urlToImage(String url) {
        try {
            InputStream inputStream = HttpsUtil.getInputStream(url);
            if (inputStream != null) {
                return ImageIO.read(inputStream);
            }
        } catch (Exception e) {
            LogUtil.error("urlToBase64", e,null);
        }
        return null;
    }

    public static String urlToBase64(String url) {
        try {
            InputStream inputStream = HttpsUtil.getInputStream(url);
            if (inputStream != null) {
                byte[] bytes = IoUtil.readInputStream(inputStream);
                return Base64Util.encode(bytes);
            }
        } catch (Exception e) {
            LogUtil.error("urlToBase64", e,null);
        }
        return "";
    }

    public static String urlToFullBase64(String url, ImageMimeType imageMimeType) {
        return getBase64Prefix(imageMimeType) + urlToBase64(url);
    }

    public static String urlToJpgBase64(String url) {
        return urlToFullBase64(url, ImageMimeType.JPG);
    }

    public static String getBase64Prefix(ImageMimeType imageMimeType) {
        return "data:" + imageMimeType.getMimeType() + ";base64,";
    }

}
